"""
客户跟进路由和视图函数
"""
from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, current_app, send_file
from flask_login import login_required, current_user
from datetime import datetime
from app import db
from app.models.customer import FollowUp, Customer, Contact
from app.models.user import User
from app.models.project import Project
from app.forms.followup import FollowUpForm, FollowUpFilterForm, SolutionSupportConfirmForm
from app.utils.helpers import permission_required, get_pagination_params
from app.utils.followup_reminder import send_followup_reminders
from sqlalchemy import func, extract
from datetime import datetime, timedelta
import io

# 创建蓝图
followup_bp = Blueprint('followup', __name__, url_prefix='/followup')


@followup_bp.route('/')
@login_required
def list_followups():
    """客户跟进列表页面"""
    page = request.args.get('page', 1, type=int)
    per_page = current_app.config.get('ITEMS_PER_PAGE', 20)
    
    # 获取筛选参数
    filter_form = FollowUpFilterForm(request.args)
    
    # 构建查询
    query = FollowUp.query
    
    # 根据用户角色过滤数据
    if current_user.role == 'sales':
        # 销售只能看到自己的跟进记录
        query = query.filter(FollowUp.manager_id == current_user.id)
    elif current_user.role == 'manager':
        # 部门负责人可以看到所有记录，但可以按人员筛选
        if filter_form.manager_id.data and filter_form.manager_id.data != 0:
            query = query.filter(FollowUp.manager_id == filter_form.manager_id.data)
    
    # 应用其他筛选条件
    if filter_form.customer_id.data and filter_form.customer_id.data != 0:
        query = query.filter(FollowUp.customer_id == filter_form.customer_id.data)
    
    if filter_form.project_id.data and filter_form.project_id.data != 0:
        query = query.filter(FollowUp.project_id == filter_form.project_id.data)
    
    if filter_form.method.data:
        query = query.filter(FollowUp.method == filter_form.method.data)
    
    if filter_form.solution_support.data:
        if filter_form.solution_support.data == 'yes':
            query = query.filter(FollowUp.solution_support == True)
        elif filter_form.solution_support.data == 'no':
            query = query.filter(FollowUp.solution_support == False)
        elif filter_form.solution_support.data == 'confirmed':
            query = query.filter(FollowUp.solution_support == True, FollowUp.solution_confirmed == True)
        elif filter_form.solution_support.data == 'pending':
            query = query.filter(FollowUp.solution_support == True, FollowUp.solution_confirmed == False)
    
    if filter_form.start_date.data:
        query = query.filter(FollowUp.followup_time >= filter_form.start_date.data)
    
    if filter_form.end_date.data:
        query = query.filter(FollowUp.followup_time <= filter_form.end_date.data)
    
    # 按跟进时间倒序排序
    query = query.order_by(FollowUp.followup_time.desc())
    
    # 分页查询
    pagination = query.paginate(page=page, per_page=per_page, error_out=False)
    followups = pagination.items
    
    # 获取关联数据
    for followup in followups:
        followup.customer = Customer.query.get(followup.customer_id)
        followup.manager = User.query.get(followup.manager_id)
        if followup.contact_id:
            followup.contact = Contact.query.get(followup.contact_id)
        if followup.solution_support_user_id:
            followup.solution_support_user = User.query.get(followup.solution_support_user_id)
    
    return render_template('followup/list.html', 
                          followups=followups, 
                          pagination=pagination,
                          filter_form=filter_form)


@followup_bp.route('/create_form')
@login_required
@permission_required('followup:create')
def create_followup_form():
    """返回创建跟进记录的表单HTML"""
    try:
        form = FollowUpForm()
        print(f"用户 {current_user.username} (角色: {current_user.role}) 请求创建跟进表单")  # 调试日志
        return render_template('followup/form_modal.html', form=form)
    except Exception as e:
        print(f"创建跟进表单出错: {str(e)}")  # 错误日志
        current_app.logger.error(f"创建跟进表单出错: {str(e)}")
        return f"表单加载失败: {str(e)}", 500


@followup_bp.route('/create', methods=['GET', 'POST'])
@login_required
@permission_required('followup:create')
def create_followup():
    """创建客户跟进记录"""
    form = FollowUpForm()
    
    if form.validate_on_submit():
        # 检查权限：销售人员只能为自己负责的客户创建跟进记录
        customer = Customer.query.get(form.customer_id.data)
        if not customer:
            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return jsonify({
                    'success': False,
                    'message': '所选客户不存在'
                })
            flash('所选客户不存在', 'error')
            return render_template('followup/form.html', form=form)
        
        if current_user.role == 'sales' and customer.manager_id != current_user.id:
            if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
                return jsonify({
                    'success': False,
                    'message': '您只能为自己负责的客户创建跟进记录'
                })
            flash('您只能为自己负责的客户创建跟进记录', 'error')
            return render_template('followup/form.html', form=form)
        
        # 创建跟进记录
        followup = FollowUp(
            customer_id=form.customer_id.data,
            project_id=form.project_id.data if form.project_id.data != 0 else None,
            manager_id=current_user.id,  # 自动设置为当前用户
            followup_time=form.followup_time.data,
            method=form.method.data,
            content=form.content.data,
            result=form.result.data,
            next_followup_time=form.next_followup_time.data,
            solution_support=form.solution_support.data,
            solution_support_user_id=form.solution_support_user_id.data if form.solution_support.data else None,
            solution_support_time=form.solution_support_time.data if form.solution_support.data else None,
            solution_confirmed=False
        )
        
        # 如果选择了联系人，设置第一个为主联系人
        if form.contact_ids.data:
            followup.contact_id = form.contact_ids.data[0]
        
        db.session.add(followup)
        db.session.commit()
        
        # 检查是否是AJAX请求
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            return jsonify({
                'success': True,
                'message': '跟进记录创建成功！'
            })
        
        flash('跟进记录创建成功！', 'success')
        
        # 如果需要解决方案人员配合，发送通知
        if form.solution_support.data and form.solution_support_user_id.data:
            # 这里可以添加发送通知的逻辑
            pass
        
        return redirect(url_for('followup.list_followups'))
    
    # 如果是POST请求但表单验证失败
    if request.method == 'POST':
        # 检查是否是AJAX请求
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            # 收集所有错误信息
            errors = {}
            for field, field_errors in form.errors.items():
                errors[field] = field_errors
            
            return jsonify({
                'success': False,
                'message': '表单验证失败，请检查输入信息',
                'errors': errors
            })
        
        # 非AJAX请求，显示错误信息
        print(f"表单验证失败: {form.errors}")  # 添加调试日志
        for field, errors in form.errors.items():
            for error in errors:
                flash(f'{field}: {error}', 'error')
    
    # 如果是GET请求或表单验证失败，返回创建表单页面
    return render_template('followup/form.html', form=form)


@followup_bp.route('/statistics')
@login_required
@permission_required('followup:view_statistics')
def statistics():
    """客户跟进统计报表"""
    # 获取当前用户
    user_id = current_user.id
    
    # 基础查询
    base_query = FollowUp.query
    
    # 根据用户角色过滤数据
    if current_user.role == 'sales':
        # 销售只能看到自己的统计数据
        base_query = base_query.filter(FollowUp.manager_id == user_id)
    
    # 总跟进次数
    total_followups = base_query.count()
    
    # 本月跟进次数
    current_month = datetime.now().month
    current_year = datetime.now().year
    month_followups = base_query.filter(
        extract('year', FollowUp.followup_time) == current_year,
        extract('month', FollowUp.followup_time) == current_month
    ).count()
    
    # 本周跟进次数
    today = datetime.now().date()
    week_start = today - timedelta(days=today.weekday())
    week_followups = base_query.filter(
        func.date(FollowUp.followup_time) >= week_start
    ).count()
    
    # 解决方案配合统计
    solution_support_count = base_query.filter(FollowUp.solution_support == True).count()
    solution_confirmed_count = base_query.filter(
        FollowUp.solution_support == True,
        FollowUp.solution_confirmed == True
    ).count()
    
    # 跟进方式统计
    method_stats = db.session.query(
        FollowUp.method,
        func.count(FollowUp.id).label('count')
    ).filter(
        *([FollowUp.manager_id == user_id] if current_user.role == 'sales' else [])
    ).group_by(FollowUp.method).all()
    
    # 每月跟进趋势（最近12个月）
    monthly_trend = []
    for i in range(11, -1, -1):
        month_date = datetime.now() - timedelta(days=30*i)
        year = month_date.year
        month = month_date.month
        month_name = month_date.strftime('%Y-%m')
        
        count = base_query.filter(
            extract('year', FollowUp.followup_time) == year,
            extract('month', FollowUp.followup_time) == month
        ).count()
        
        monthly_trend.append({
            'month': month_name,
            'count': count
        })
    
    # 销售人员跟进统计（仅管理员和部门负责人可见）
    sales_stats = []
    if current_user.role in ['admin', 'manager']:
        sales_stats = db.session.query(
            User.username,
            func.count(FollowUp.id).label('count')
        ).join(
            FollowUp, User.id == FollowUp.manager_id
        ).filter(
            User.role == 'sales'
        ).group_by(
            User.id, User.username
        ).order_by(
            func.count(FollowUp.id).desc()
        ).all()
    
    # 即将到期的跟进记录（未来7天内）
    upcoming_followups = FollowUp.get_upcoming_followups(days=7)
    if current_user.role == 'sales':
        upcoming_followups = [f for f in upcoming_followups if f.manager_id == user_id]
    
    # 过期的跟进记录
    overdue_followups = FollowUp.get_overdue_followups()
    if current_user.role == 'sales':
        overdue_followups = [f for f in overdue_followups if f.manager_id == user_id]
    
    # 待确认解决方案配合的记录
    pending_solution_support = FollowUp.get_solution_support_pending()
    if current_user.role == 'sales':
        pending_solution_support = [f for f in pending_solution_support if f.manager_id == user_id]
    
    # 获取关联数据
    for followup in upcoming_followups + overdue_followups + pending_solution_support:
        followup.customer = Customer.query.get(followup.customer_id)
        followup.manager = User.query.get(followup.manager_id)
    
    return render_template('followup/statistics.html',
                          total_followups=total_followups,
                          month_followups=month_followups,
                          week_followups=week_followups,
                          solution_support_count=solution_support_count,
                          solution_confirmed_count=solution_confirmed_count,
                          method_stats=method_stats,
                          monthly_trend=monthly_trend,
                          sales_stats=sales_stats,
                          upcoming_followups=upcoming_followups,
                          overdue_followups=overdue_followups,
                          pending_solution_support=pending_solution_support)


@followup_bp.route('/export/statistics')
@login_required
@permission_required('followup:view_statistics')
def export_statistics():
    """导出客户跟进统计报表"""
    # 检查权限
    if current_user.role not in ['admin', 'manager']:
        flash('您没有权限导出统计报表', 'danger')
        return redirect(url_for('followup.statistics'))
    
    # 获取统计数据
    total_followups = FollowUp.query.count()
    
    # 获取本月跟进次数
    current_month = datetime.now().month
    current_year = datetime.now().year
    monthly_followups = FollowUp.query.filter(
        extract('month', FollowUp.followup_time) == current_month,
        extract('year', FollowUp.followup_time) == current_year
    ).count()
    
    # 获取本周跟进次数
    today = datetime.now().date()
    week_start = today - timedelta(days=today.weekday())
    weekly_followups = FollowUp.query.filter(
        FollowUp.followup_time >= week_start
    ).count()
    
    # 获取解决方案配合统计
    solution_total = FollowUp.query.filter(FollowUp.solution_support == True).count()
    solution_confirmed = FollowUp.query.filter(
        FollowUp.solution_support == True,
        FollowUp.solution_confirmed == True
    ).count()
    
    # 获取跟进方式统计
    method_stats = db.session.query(
        FollowUp.method, func.count(FollowUp.id)
    ).group_by(FollowUp.method).all()
    
    # 获取每月跟进趋势（最近12个月）
    monthly_trend = []
    for i in range(12):
        month = (current_month - i - 1) % 12 + 1
        year = current_year if (current_month - i - 1) >= 0 else current_year - 1
        month_name = f"{year}-{month:02d}"
        
        count = FollowUp.query.filter(
            extract('month', FollowUp.followup_time) == month,
            extract('year', FollowUp.followup_time) == year
        ).count()
        
        monthly_trend.append({
            'month': month_name,
            'count': count
        })
    
    # 反转列表，使时间顺序正确
    monthly_trend = list(reversed(monthly_trend))
    
    # 获取销售人员跟进统计
    sales_stats = db.session.query(
        User.username,
        func.count(FollowUp.id).label('total'),
        func.sum(
            func.case(
                (extract('month', FollowUp.followup_time) == current_month) &
                (extract('year', FollowUp.followup_time) == current_year), 1,
                else_=0
            )
        ).label('monthly'),
        func.sum(
            func.case(
                (FollowUp.solution_support == True), 1,
                else_=0
            )
        ).label('solution_total'),
        func.sum(
            func.case(
                (FollowUp.solution_support == True) &
                (FollowUp.solution_confirmed == True), 1,
                else_=0
            )
        ).label('solution_confirmed')
    ).join(FollowUp, User.id == FollowUp.manager_id).group_by(User.id, User.username).all()
    
    # 转换为字典格式
    sales_stats = [
        {
            'username': stat.username,
            'total': stat.total,
            'monthly': int(stat.monthly or 0),
            'solution_total': int(stat.solution_total or 0),
            'solution_confirmed': int(stat.solution_confirmed or 0)
        }
        for stat in sales_stats
    ]
    
    # 获取即将到期的跟进记录
    upcoming_followups = FollowUp.get_upcoming_followups(7)
    
    # 获取已过期的跟进记录
    overdue_followups = FollowUp.get_overdue_followups()
    
    # 获取待确认解决方案配合的跟进记录
    solution_pending = FollowUp.get_solution_support_pending()
    
    # 创建Excel工作簿
    from openpyxl import Workbook
    import io
    from flask import send_file
    
    wb = Workbook()
    
    # 创建总体统计工作表
    ws1 = wb.active
    ws1.title = "总体统计"
    ws1.append(["统计项目", "数值"])
    ws1.append(["总跟进次数", total_followups])
    ws1.append(["本月跟进次数", monthly_followups])
    ws1.append(["本周跟进次数", weekly_followups])
    ws1.append(["解决方案配合总数", solution_total])
    ws1.append(["已确认解决方案配合", solution_confirmed])
    ws1.append(["解决方案配合率", f"{solution_confirmed/solution_total*100:.1f}%" if solution_total > 0 else "0%"])
    
    # 创建跟进方式统计工作表
    ws2 = wb.create_sheet("跟进方式统计")
    ws2.append(["跟进方式", "次数"])
    for stat in method_stats:
        ws2.append([stat[0], stat[1]])
    
    # 创建每月跟进趋势工作表
    ws3 = wb.create_sheet("每月跟进趋势")
    ws3.append(["月份", "跟进次数"])
    for trend in monthly_trend:
        ws3.append([trend['month'], trend['count']])
    
    # 创建销售人员跟进统计工作表
    ws4 = wb.create_sheet("销售人员跟进统计")
    ws4.append(["销售人员", "总跟进次数", "本月跟进次数", "解决方案配合总数", "已确认解决方案配合"])
    for stat in sales_stats:
        ws4.append([
            stat['username'],
            stat['total'],
            stat['monthly'],
            stat['solution_total'],
            stat['solution_confirmed']
        ])
    
    # 创建即将到期跟进记录工作表
    ws5 = wb.create_sheet("即将到期跟进记录")
    ws5.append(["客户名称", "跟进时间", "跟进内容", "跟进人"])
    for followup in upcoming_followups:
        followup.customer = Customer.query.get(followup.customer_id)
        followup.manager = User.query.get(followup.manager_id)
        ws5.append([
            followup.customer.name if followup.customer else "",
            followup.next_followup_time.strftime('%Y-%m-%d') if followup.next_followup_time else "",
            followup.content,
            followup.manager.username if followup.manager else ""
        ])
    
    # 创建已过期跟进记录工作表
    ws6 = wb.create_sheet("已过期跟进记录")
    ws6.append(["客户名称", "跟进时间", "跟进内容", "跟进人"])
    for followup in overdue_followups:
        followup.customer = Customer.query.get(followup.customer_id)
        followup.manager = User.query.get(followup.manager_id)
        ws6.append([
            followup.customer.name if followup.customer else "",
            followup.next_followup_time.strftime('%Y-%m-%d') if followup.next_followup_time else "",
            followup.content,
            followup.manager.username if followup.manager else ""
        ])
    
    # 创建待确认解决方案配合工作表
    ws7 = wb.create_sheet("待确认解决方案配合")
    ws7.append(["客户名称", "解决方案配合人", "跟进内容", "跟进人"])
    for followup in solution_pending:
        followup.customer = Customer.query.get(followup.customer_id)
        followup.manager = User.query.get(followup.manager_id)
        followup.solution_support_user = User.query.get(followup.solution_support_user_id) if followup.solution_support_user_id else None
        ws7.append([
            followup.customer.name if followup.customer else "",
            followup.solution_support_user.username if followup.solution_support_user else "",
            followup.content,
            followup.manager.username if followup.manager else ""
        ])
    
    # 保存Excel文件到内存
    excel_file = io.BytesIO()
    wb.save(excel_file)
    excel_file.seek(0)
    
    # 生成文件名
    filename = f"客户跟进统计报表_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
    
    # 返回文件下载
    return send_file(
        excel_file,
        as_attachment=True,
        download_name=filename,
        mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    )


@followup_bp.route('/<int:followup_id>')
@login_required
def view_followup(followup_id):
    """查看客户跟进详情"""
    followup = FollowUp.query.get_or_404(followup_id)
    
    # 权限检查
    if current_user.role == 'sales' and followup.manager_id != current_user.id:
        flash('您没有权限查看此跟进记录', 'danger')
        return redirect(url_for('followup.list_followups'))
    
    # 获取关联数据
    followup.customer = Customer.query.get(followup.customer_id)
    followup.manager = User.query.get(followup.manager_id)
    if followup.contact_id:
        followup.contact = Contact.query.get(followup.contact_id)
    if followup.solution_support_user_id:
        followup.solution_support_user = User.query.get(followup.solution_support_user_id)
    if followup.project_id:
        followup.project = Project.query.get(followup.project_id)
    
    # 获取客户历史项目
    projects = Project.query.filter_by(customer_id=followup.customer_id).all()
    
    # 获取当前用户的在跟项目
    if current_user.role == 'sales':
        user_projects = Project.query.filter_by(
            customer_id=followup.customer_id, 
            manager_id=current_user.id
        ).all()
    else:
        user_projects = projects
    
    return render_template('followup/detail.html', 
                          followup=followup, 
                          projects=projects,
                          user_projects=user_projects)


@followup_bp.route('/<int:followup_id>/edit', methods=['GET', 'POST'])
@login_required
@permission_required('followup:edit')
def edit_followup(followup_id):
    """编辑客户跟进记录"""
    followup = FollowUp.query.get_or_404(followup_id)
    
    # 权限检查
    if current_user.role == 'sales' and followup.manager_id != current_user.id:
        flash('您没有权限编辑此跟进记录', 'danger')
        return redirect(url_for('followup.list_followups'))
    
    form = FollowUpForm(obj=followup)
    
    if form.validate_on_submit():
        # 更新跟进记录
        followup.customer_id = form.customer_id.data
        followup.project_id = form.project_id.data if form.project_id.data != 0 else None
        followup.followup_time = form.followup_time.data
        followup.method = form.method.data
        followup.content = form.content.data
        followup.result = form.result.data
        followup.next_followup_time = form.next_followup_time.data
        followup.solution_support = form.solution_support.data
        followup.solution_support_user_id = form.solution_support_user_id.data if form.solution_support.data else None
        followup.solution_support_time = form.solution_support_time.data if form.solution_support.data else None
        
        # 如果选择了联系人，设置第一个为主联系人
        if form.contact_ids.data:
            followup.contact_id = form.contact_ids.data[0]
        else:
            followup.contact_id = None
        
        db.session.commit()
        
        flash('跟进记录更新成功！', 'success')
        return redirect(url_for('followup.view_followup', followup_id=followup.id))
    
    # 设置表单的联系人选项
    customer = Customer.query.get(followup.customer_id)
    if customer:
        form.contact_ids.choices = [(c.id, c.name) for c in customer.contacts]
        if followup.contact_id:
            form.contact_ids.data = [followup.contact_id]
    
    return render_template('followup/form.html', form=form, followup=followup, title='编辑跟进记录')


@followup_bp.route('/<int:followup_id>/delete', methods=['POST'])
@login_required
@permission_required('followup:delete')
def delete_followup(followup_id):
    """删除客户跟进记录"""
    followup = FollowUp.query.get_or_404(followup_id)
    
    # 权限检查
    if current_user.role == 'sales' and followup.manager_id != current_user.id:
        flash('您没有权限删除此跟进记录', 'danger')
        return redirect(url_for('followup.list_followups'))
    
    db.session.delete(followup)
    db.session.commit()
    
    flash('跟进记录删除成功！', 'success')
    return redirect(url_for('followup.list_followups'))


@followup_bp.route('/<int:followup_id>/confirm_solution', methods=['GET', 'POST'])
@login_required
@permission_required('followup:confirm_solution')
def confirm_solution_support(followup_id):
    """确认解决方案人员配合"""
    followup = FollowUp.query.get_or_404(followup_id)
    
    # 权限检查：只有解决方案人员本人或管理员可以确认
    if (current_user.id != followup.solution_support_user_id and 
        current_user.role not in ['admin', 'manager']):
        flash('您没有权限确认此配合请求', 'danger')
        return redirect(url_for('followup.view_followup', followup_id=followup.id))
    
    form = SolutionSupportConfirmForm()
    
    if form.validate_on_submit():
        if form.confirmed.data:
            followup.solution_confirmed = True
            followup.solution_support_time = datetime.now()
            db.session.commit()
            flash('已确认配合请求！', 'success')
        else:
            flash('已拒绝配合请求！', 'info')
        
        return redirect(url_for('followup.view_followup', followup_id=followup.id))
    
    return render_template('followup/confirm_solution.html', 
                          form=form, 
                          followup=followup)


@followup_bp.route('/api/customer/<int:customer_id>/contacts')
@login_required
def get_customer_contacts(customer_id):
    """获取客户的联系人列表API"""
    from app.services import CustomerService
    
    # 检查是否有权限访问该客户
    customer = CustomerService.get_customer(customer_id)
    if not customer:
        return jsonify({'error': '无权限访问该客户'}), 403
    
    # 获取联系人列表
    contacts = CustomerService.get_customer_contacts(customer_id)
    if contacts is None:
        return jsonify({'error': '无权限获取该客户联系人'}), 403
    
    # 转换为JSON格式
    contacts_data = []
    for contact in contacts:
        contacts_data.append({
            'id': contact.id,
            'name': contact.name,
            'position': contact.position,
            'phone': contact.phone,
            'email': contact.email,
            'is_primary': contact.is_primary
        })
    
    return jsonify(contacts_data)


@followup_bp.route('/api/customers/<int:customer_id>/projects')
@login_required
def get_customer_projects(customer_id):
    """获取客户的项目列表（AJAX接口）"""
    customer = Customer.query.get_or_404(customer_id)
    
    # 获取所有项目
    all_projects = Project.query.filter_by(customer_id=customer_id).all()
    
    # 获取当前用户的在跟项目
    if current_user.role == 'sales':
        user_projects = Project.query.filter_by(
            customer_id=customer_id, 
            manager_id=current_user.id
        ).all()
    else:
        user_projects = all_projects
    
    # 构建返回数据
    project_data = {
        'all_projects': [{'id': p.id, 'name': p.name, 'status': p.status} for p in all_projects],
        'user_projects': [{'id': p.id, 'name': p.name, 'status': p.status} for p in user_projects]
    }
    
    return jsonify(project_data)


@followup_bp.route('/api/customers/<int:customer_id>')
@login_required
def get_customer_info(customer_id):
    """获取客户信息（AJAX接口）"""
    customer = Customer.query.get_or_404(customer_id)
    
    # 构建返回数据
    customer_data = {
        'id': customer.id,
        'name': customer.name,
        'customer_number': customer.customer_number,
        'industry': customer.industry,
        'source': customer.source,
        'status': customer.status,
        'description': customer.description
    }
    
    return jsonify(customer_data)


@followup_bp.route('/api/customers/<int:customer_id>/followups')
@login_required
def get_customer_followups(customer_id):
    """获取客户的跟进记录（AJAX接口）"""
    customer = Customer.query.get_or_404(customer_id)
    
    # 构建查询
    query = FollowUp.query.filter_by(customer_id=customer_id)
    
    # 根据用户角色过滤数据
    if current_user.role == 'sales':
        # 销售只能看到自己的跟进记录
        query = query.filter(FollowUp.manager_id == current_user.id)
    
    # 按跟进时间倒序排序，限制返回最近10条记录
    followups = query.order_by(FollowUp.followup_time.desc()).limit(10).all()
    
    # 构建返回数据
    followup_list = []
    for followup in followups:
        manager = User.query.get(followup.manager_id)
        followup_data = {
            'id': followup.id,
            'followup_time': followup.followup_time.isoformat(),
            'method': followup.method,
            'content': followup.content,
            'user_name': manager.username if manager else '未知'
        }
        followup_list.append(followup_data)
    
    return jsonify({'followups': followup_list})


@followup_bp.route('/send_reminders', methods=['POST'])
@login_required
@permission_required('followup:send_reminders')
def send_reminders():
    """手动发送跟进提醒"""
    try:
        success, message = send_followup_reminders()
        if success:
            flash(message, 'success')
        else:
            flash(message, 'danger')
    except Exception as e:
        flash(f'发送提醒时发生错误: {str(e)}', 'danger')
    
    return redirect(url_for('followup.list_followups'))